<?php

namespace ApiBundle\Controller\Admin;

use ApiBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;

class AuthController extends BaseController
{
    /*
     * 登录
     */
    public function loginAction(Request $request)
    {
        $phone = $request->get('phone');
        $password = $request->get("password");

        $validations = $this->get("helper.validations");
        $strings = $this->get("helper.strings");

        if(!$validations->isMobile($phone)){
            return $this->jsonResponse(1,"手机号格式不正确");
        }

        if(!$validations->isPassword($password)){
            return $this->jsonResponse(1,"密码为6~18位");
        }

        // TODO: 判断手机号是否注册
        $conn = $this->get("database_connection");
        $user = $conn->fetchAssoc("SELECT * FROM admin WHERE phone = '". $phone ."'");
        if(!$user){
            return $this->jsonResponse(1,"手机号尚未注册");
        }


        if($user['status'] == 0){

            return $this->jsonResponse(1,"帐号已被禁用");
        }

        $entry_password = $strings->encryptPassword($password,$user['salt']);

        if($user['password'] != $entry_password){
            return $this->jsonResponse(1,"密码错误");
        }

        $token = $strings->generateToken($phone);
        $data = array(
            "token" => $token
        );
        $where = array(
            "id" => $user['id']
        );

        $conn->update("admin",$data,$where);

        $this->get("session")->set("admin_id",$user['id']);
        $this->get("session")->set("district_id",$user['district_id']);
        $this->get("session")->set("admin_role_id",$user['admin_role_id']);
        $this->get("session")->set("admin_name",$user['realname']);

        return $this->jsonResponse(0,"操作成功",array("token" => $token));

    }

    /*
     * 找回密码
     */
    public function forgetPasswordAction(Request $request)
    {
        $phone = $request->request->get("phone");
        $role = $request->request->get("role");
        $validation_code = $request->request->get("validation_code");
        $password = $request->request->get("password");
        $comfire_password = $request->request->get("comfire_password");

        $validations = $this->get("helper.validations");
        $serviceStrings = $this->get("helper.strings");

        if(!$phone || !$validations->isMobile($phone))
        {
            return $this->jsonResponse(1,"手机号格式不正确");
        }
        if(empty($validation_code)){
            return $this->jsonResponse(1,"请输入验证码");
        }

        // TODO: 短信验证
        $message_error = $this->checkSMSSalt($phone, $validation_code, 3, $role);
        if($message_error){
            return $this->jsonResponse(1,$message_error);
        }

        if(!$password || !$validations->isPassword($password))
        {
            return $this->jsonResponse(2,"密码为6~18位");
        }

        if(!$comfire_password || $comfire_password != $password){
            return $this->jsonResponse(2,"确认密码与密码不统一");
        }
        $conn = $this->get("database_connection");
        $select = $conn->fetchAssoc("SELECT * FROM admin WHERE phone = '". $phone ."'");
        if(!$select){
            return $this->jsonResponse(1,"用户不存在");
        }
        $salt = $select['salt'];
        $encryptPassword = $serviceStrings->encryptPassword($password,$salt);
        $data = array(
            "password"=>$encryptPassword
        );
        $where = array(
            "phone"=>$phone
        );

        $update = $conn->update("admin",$data,$where);


        return $this->jsonResponse(0,"找回密码成功",$update);

    }

    /*
     * 获取管理员个人信息
     */
    public function selfInformationAction()
    {
        if(!$this->isAdminLogged()){
            return $this->admin_response;
        }

        $conn = $this->get("database_connection");
        $admin = $conn->fetchAssoc("SELECT a.*, d.name as district_name FROM admin a LEFT JOIN district d ON a.district_id = d.id WHERE a.id = '". $this->getAdminId() ."'");

        return $this->jsonResponse(0,"操作成功",$admin);
    }

    /*
     * 编辑个人信息
     */
    public function editSelfInformationAction(Request $request)
    {
        if(!$this->isAdminLogged()){
            return $this->admin_response;
        }

        $conn = $this->get("database_connection");
        $validations = $this->get("helper.validations");

        $admin = $conn->fetchAssoc("SELECT * FROM admin WHERE id = '". $this->getAdminId() ."'");


        $email = $request->get("email");
        $nickname = $request->get("nickname");

        if(empty($email) || empty($nickname)){
            return $this->jsonResponse(1,"参数错误");
        }


        if(!$validations->isEmail($email)){
            return $this->jsonResponse(1,"邮箱格式错误");
        }

        $data = array(
            "email" => $email,
            "nickname" => $nickname
        );


//        if($admin['admin_role_id'] != "1" && $admin['admin_role_id'] != "2"){
//            $phone = $request->get("phone");
//            $new_admin_role_id = $request->get("admin_role_id");
//
//            if(empty($phone) || empty($new_admin_role_id)){
//                return $this->jsonResponse(1,"参数错误");
//            }
//            if(!$validations->isMobile($phone)){
//                return $this->jsonResponse(1,"手机号格式错误");
//            }
//
//            // 判断手机号是否存在
//            if($this->checkPhoneExit($phone)){
//                return $this->jsonResponse(1,"手机号已存在");
//            }
//            $data['phone'] = $phone;
//            $data['admin_role_id'] = $new_admin_role_id;
//        }

        $where = array(
            "id" => $this->getAdminId()
        );
        $conn->update("admin",$data,$where);



        return $this->jsonResponse(0,"操作成功",$data);
    }

    /*
     * 修改密码
     */
    public function updatePasswordAction(Request $request)
    {
        $conn = $this->get("database_connection");
        if(!$this->isAdminLogged()){
            return $this->admin_response;
        }
        $password = $request->get("password");
        $new_password = $request->get("new_password");
        $comfirm_password = $request->get("comfirm_password");

        // TODO: 验证
        $validations = $this->get("helper.validations");
        $strings = $this->get("helper.strings");

        if(!$validations->isPassword($new_password)){
            return $this->jsonResponse(1,"密码为6~18位");
        }
        if($new_password != $comfirm_password){
            return $this->jsonResponse(1,"密码与确认密码不一致");
        }

        // TODO： 查询
        $admin = $conn->fetchAssoc("SELECT * FROM admin WHERE id = '". $this->getAdminId() ."'");

        $password = $strings->encryptPassword($password,$admin['salt']);

        // TODO: 原密码判断
        if($admin['password'] != $password){
            return $this->jsonResponse(1,"原密码错误");
        }

        $encrypt_salt = $strings->generateSalt(6,true);
        $encrypt_password = $strings->encryptPassword($new_password,$encrypt_salt);

        $data = array(
            "password" => $encrypt_password,
            "salt" => $encrypt_salt
        );

        $conn->update("admin",$data,array("id" => $this->getAdminId() ));


        return $this->jsonResponse(0,"操作成功");
    }
    /*
     * 退出登录
     */
    public function logoutAction()
    {
        $conn = $this->get("database_connection");

//        if(!$this->isAdminLogged()){
//            return $this->admin_response;
//        }

        $conn->update("admin",array("token"=>NULL),array("id"=>$this->getAdminId()));

        $this->get("session")->clear();

        return $this->jsonResponse(0,"操作成功");
    }
}
